package com.hubing.cloud.app.web.es.query;

import java.util.ArrayList;
import java.util.List;

public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {

	private final List<QueryBuilder> mustClauses    = new ArrayList();
	private final List<QueryBuilder> shouldClauses  = new ArrayList();
	private final List<QueryBuilder> mustNotClauses = new ArrayList();
	private final List<QueryBuilder> filterClauses  = new ArrayList();

	public BoolQueryBuilder must(QueryBuilder queryBuilder) {
		if (queryBuilder == null) {
			throw new IllegalArgumentException("inner bool query clause cannot be null");
		} else {
			this.mustClauses.add(queryBuilder);
			return this;
		}
	}

	public BoolQueryBuilder mustNot(QueryBuilder queryBuilder) {
		if (queryBuilder == null) {
			throw new IllegalArgumentException("inner bool query clause cannot be null");
		} else {
			this.mustNotClauses.add(queryBuilder);
			return this;
		}
	}

	public BoolQueryBuilder filter(QueryBuilder queryBuilder) {
		if (queryBuilder == null) {
			throw new IllegalArgumentException("inner bool query clause cannot be null");
		} else {
			this.filterClauses.add(queryBuilder);
			return this;
		}
	}

	public BoolQueryBuilder should(QueryBuilder queryBuilder) {
		if (queryBuilder == null) {
			throw new IllegalArgumentException("inner bool query clause cannot be null");
		} else {
			this.shouldClauses.add(queryBuilder);
			return this;
		}
	}

	public boolean hasClauses() {
		return !this.mustClauses.isEmpty() || !this.shouldClauses.isEmpty() || !this.mustNotClauses.isEmpty() ||
				!this.filterClauses.isEmpty();
	}

	@Override
	public String toDocument() {
		StringBuilder document = new StringBuilder();
		document.append("{ \"bool\": ");
		document.append("{ \"must\":[ ");
		for (int i = 0; i < mustClauses.size(); i++) {
			document.append(mustClauses.get(i).toDocument());
			if (i < mustClauses.size() - 1) {
				document.append(",");
			}
		}
		document.append("],");
		document.append(" \"should\":[ ");
		for (int i = 0; i < shouldClauses.size(); i++) {
			document.append(shouldClauses.get(i).toDocument());
			if (i < shouldClauses.size() - 1) {
				document.append(",");
			}
		}
		document.append("],");
		document.append("\"must_not\":[ ");
		for (int i = 0; i < mustNotClauses.size(); i++) {
			document.append(mustNotClauses.get(i).toDocument());
			if (i < mustNotClauses.size() - 1) {
				document.append(",");
			}
		}
		document.append("],");
		document.append(" \"filter\":[ ");
		for (int i = 0; i < filterClauses.size(); i++) {
			document.append(filterClauses.get(i).toDocument());
			if (i < filterClauses.size() - 1) {
				document.append(",");
			}
		}
		document.append("]}}");
		return document.toString();
	}

	@Override
	public String toString() {
		return toDocument();
	}
}
